<template>
  <div class="adoption-list-container">
    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <el-card shadow="hover">
        <div class="search-form">
          <!-- 品种搜索 -->
          <div class="search-item">
            <label>品种</label>
            <el-input 
              v-model="searchForm.breed" 
              placeholder="请输入品种" 
              clearable
              @clear="handleSearch">
            </el-input>
          </div>

          <!-- 搜索按钮 -->
          <div class="search-buttons">
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            <el-button icon="el-icon-refresh-left" @click="handleReset">重置</el-button>
            <el-button type="success" icon="el-icon-plus" @click="showAddDialog">发布领养帖子</el-button>
            <el-button 
              type="info" 
              icon="el-icon-star-off" 
              @click="toggleFavoriteFilter"
              v-if="false && hasFavoritePosts">
              我的收藏
            </el-button>
          </div>
        </div>

        <!-- 筛选按钮区域 -->
        <div class="filter-section">
          <div class="filter-group">
            <label>宠物类型：</label>
            <div class="filter-buttons">
              <div 
                class="filter-btn" 
                :class="{ active: searchForm.petType === '' }"
                @click="filterByPetType('')">
                全部
              </div>
              <div 
                class="filter-btn"
                :class="{ active: searchForm.petType === '狗' }"
                @click="filterByPetType('狗')">
                狗
              </div>
              <div 
                class="filter-btn"
                :class="{ active: searchForm.petType === '猫' }"
                @click="filterByPetType('猫')">
                猫
              </div>
            </div>
          </div>

          <div class="filter-group">
            <label>宠物性别：</label>
            <div class="filter-buttons">
              <div 
                class="filter-btn" 
                :class="{ active: searchForm.petGender === '' }"
                @click="filterByGender('')">
                全部
              </div>
              <div 
                class="filter-btn"
                :class="{ active: searchForm.petGender === '公' }"
                @click="filterByGender('公')">
                公
              </div>
              <div 
                class="filter-btn"
                :class="{ active: searchForm.petGender === '母' }"
                @click="filterByGender('母')">
                母
              </div>
            </div>
          </div>

          <div class="filter-group">
            <label>发布者：</label>
            <div class="filter-buttons">
              <div 
                class="filter-btn" 
                :class="{ active: searchForm.publisher === '' }"
                @click="filterByPublisher('')">
                全部
              </div>
              <div 
                class="filter-btn"
                :class="{ active: searchForm.publisher === 'my' }"
                @click="filterByPublisher('my')">
                我发布的
              </div>
              <div 
                class="filter-btn"
                :class="{ active: searchForm.publisher === 'other' }"
                @click="filterByPublisher('other')">
                他人发布的
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 领养帖子网格展示 -->
    <div class="adoption-grid">
      <el-row :gutter="20">
        <el-col 
          v-for="post in adoptionList" 
          :key="post.id"
          :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
          <div class="adoption-card" @click="viewDetail(post.id)">
            <div class="adoption-image">
              <img 
                v-if="!post.imageLoadError"
                :src="getFirstImage(post.photos)" 
                :alt="post.title"
                @error="handleImageLoadError(post)">
              <div v-else class="image-error">
                <i class="el-icon-picture-outline"></i>
                <span>图片加载失败</span>
              </div>
              <div class="adoption-overlay">
                <el-button type="primary" size="small" icon="el-icon-view">查看详情</el-button>
              </div>
              <!-- 我的帖子标识 -->
              <div v-if="isMyPost(post.userId)" class="my-post-badge">我的发布</div>
            </div>
            <div class="adoption-info">
              <div class="adoption-title" :title="post.title">{{ post.title }}</div>
              <div class="adoption-meta">
                <el-tag size="small" type="success">{{ post.petType }}</el-tag>
                <el-tag size="small" type="warning">{{ post.petGender }}</el-tag>
                <el-tag size="small" type="info">{{ post.breed }}</el-tag>
              </div>
              <div class="adoption-pet-name">宠物：{{ post.petName }}</div>
              <div class="adoption-location" v-if="post.location">
                <i class="el-icon-location"></i>
                {{ post.location }}
              </div>
              <div class="adoption-footer">
                <div class="user-info">
                  <img 
                    v-if="!post.avatarLoadError"
                    :src="post.userAvatar || 'https://img1.baidu.com/it/u=1537776144,3012351076&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'" 
                    :alt="post.userNickname" 
                    class="user-avatar"
                    @error="handleAvatarLoadError(post)">
                  <div v-else class="avatar-error"></div>
                  <span class="user-nickname">{{ post.userNickname || '匿名用户' }}</span>
                </div>
                <!-- 我的帖子显示操作按钮 -->
                <div v-if="isMyPost(post.userId)" class="action-buttons">
                  <el-button 
                    type="warning" 
                    size="mini" 
                    icon="el-icon-edit"
                    @click.stop="editPost(post)">
                    编辑
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 空状态 -->
      <el-empty v-if="adoptionList.length === 0" description="暂无领养帖子"></el-empty>
    </div>

    <!-- 分页 -->
    <div class="pagination-section" v-if="total > 0">
      <el-pagination
        background
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 发布/编辑领养帖子弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="700px"
      :close-on-click-modal="false">
      <el-form :model="postForm" label-width="100px" ref="postForm">
        <el-form-item label="标题" required>
          <el-input v-model="postForm.title" placeholder="请输入标题" maxlength="200"></el-input>
        </el-form-item>
        
        <el-form-item label="宠物类型" required>
          <el-radio-group v-model="postForm.petType">
            <el-radio label="狗">狗</el-radio>
            <el-radio label="猫">猫</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="宠物性别" required>
          <el-radio-group v-model="postForm.petGender">
            <el-radio label="公">公</el-radio>
            <el-radio label="母">母</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="宠物名称" required>
          <el-input v-model="postForm.petName" placeholder="请输入宠物名称" maxlength="50"></el-input>
        </el-form-item>
        
        <el-form-item label="品种" required>
          <el-input v-model="postForm.breed" placeholder="请输入品种" maxlength="100"></el-input>
        </el-form-item>
        
        <el-form-item label="疫苗情况">
          <el-input 
            type="textarea" 
            v-model="postForm.vaccineStatus" 
            placeholder="请输入疫苗接种情况" 
            :rows="3"
            maxlength="500"></el-input>
        </el-form-item>
        
        <el-form-item label="照片上传">
          <el-upload
            :action="uploadUrl"
            list-type="picture-card"
            :file-list="fileList"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :limit="5"
            :on-exceed="handleExceed">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">最多上传5张图片，每张不超过5MB</div>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="领养要求">
          <el-input 
            type="textarea" 
            v-model="postForm.adoptionRequirement" 
            placeholder="请输入领养要求" 
            :rows="4"
            maxlength="1000"></el-input>
        </el-form-item>
        
        <el-form-item label="地理位置">
          <el-input v-model="postForm.location" placeholder="请输入地理位置" maxlength="200"></el-input>
        </el-form-item>
        
        <el-form-item label="主人信息">
          <el-input 
            type="textarea" 
            v-model="postForm.ownerInfo" 
            placeholder="请输入主人联系方式等信息" 
            :rows="3"
            maxlength="500"></el-input>
        </el-form-item>
        
        <el-form-item label="状态" v-if="isEdit">
          <el-radio-group v-model="postForm.status">
            <el-radio label="寻找中">寻找中</el-radio>
            <el-radio label="已结束">已结束</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input 
            type="textarea" 
            v-model="postForm.description" 
            placeholder="请输入详细描述" 
            :rows="5"
            maxlength="2000"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPost">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserAdoptionList, addAdoptionPost, updateAdoptionPost } from '@/api/adoption';

export default {
  name: 'UserAdoptionList',
  data() {
    return {
      searchForm: {
        breed: '',
        petType: '',
        petGender: '',
        publisher: ''
      },
      adoptionList: [],
      currentPage: 1,
      pageSize: 12,
      total: 0,
      loading: false,
      
      // 弹窗相关
      dialogVisible: false,
      dialogTitle: '发布领养帖子',
      isEdit: false,
      postForm: {
        id: null,
        title: '',
        description: '',
        petType: '狗',
        petGender: '公',
        petName: '',
        breed: '',
        vaccineStatus: '',
        photos: '',
        adoptionRequirement: '',
        location: '',
        ownerInfo: '',
        status: '寻找中'
      },
      
      // 图片上传相关
      uploadUrl: 'http://47.97.154.151:18001/api/file/upload',
      fileList: [],
      uploadedImages: [],
      hasFavoritePosts: false
    };
  },
  created() {
    this.loadAdoptionPosts();
  },
  methods: {
    // 加载领养帖子列表
    async loadAdoptionPosts() {
      this.loading = true;
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          currentUserId: userInfo ? userInfo.id : null
        };
        
        if (this.searchForm.breed) {
          params.breed = this.searchForm.breed;
        }
        if (this.searchForm.petType) {
          params.petType = this.searchForm.petType;
        }
        if (this.searchForm.petGender) {
          params.petGender = this.searchForm.petGender;
        }
        if (this.searchForm.publisher) {
          params.publisher = this.searchForm.publisher;
        }
        
        const response = await getUserAdoptionList(params);
        if (response.data.success) {
          this.adoptionList = response.data.data.records || [];
          this.total = response.data.data.total || 0;
        } else {
          this.$notify({
            title: '失败',
            message: response.data.message || '加载领养帖子失败',
            type: 'error',
            duration: 2000
          });
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: '加载领养帖子失败，请稍后重试',
          type: 'error',
          duration: 2000
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.loadAdoptionPosts();
    },
    
    // 重置
    handleReset() {
      this.searchForm = {
        breed: '',
        petType: '',
        petGender: '',
        publisher: ''
      };
      this.handleSearch();
    },
    
    // 按宠物类型筛选
    filterByPetType(petType) {
      this.searchForm.petType = petType;
      this.handleSearch();
    },
    
    // 按性别筛选
    filterByGender(gender) {
      this.searchForm.petGender = gender;
      this.handleSearch();
    },
    
    // 按发布者筛选
    filterByPublisher(publisher) {
      this.searchForm.publisher = publisher;
      this.handleSearch();
    },
    
    // 翻页
    handlePageChange(page) {
      this.currentPage = page;
      this.loadAdoptionPosts();
      window.scrollTo({ top: 0, behavior: 'smooth' });
    },
    
    // 获取第一张图片
    getFirstImage(photos) {
      if (!photos) {
        return 'https://img1.baidu.com/it/u=2531584226,2194794184&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500';
      }
      const imageArray = photos.split(',');
      return imageArray[0] || 'https://img1.baidu.com/it/u=2531584226,2194794184&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500';
    },
    
    // 判断是否是我的帖子
    isMyPost(userId) {
      const userInfo = JSON.parse(localStorage.getItem('userInfo'));
      return userInfo && userInfo.id === userId;
    },
    
    // 查看详情
    viewDetail(id) {
      this.$router.push(`/user/adoption-detail/${id}`);
    },
    
    // 显示发布弹窗
    showAddDialog() {
      const userInfo = JSON.parse(localStorage.getItem('userInfo'));
      if (!userInfo) {
        this.$notify({
          title: '提示',
          message: '请先登录',
          type: 'warning',
          duration: 2000
        });
        this.$router.push('/login');
        return;
      }
      
      this.isEdit = false;
      this.dialogTitle = '发布领养帖子';
      this.resetForm();
      this.dialogVisible = true;
    },
    
    // 编辑帖子
    editPost(post) {
      this.isEdit = true;
      this.dialogTitle = '编辑领养帖子';
      this.postForm = {
        id: post.id,
        title: post.title,
        description: post.description || '',
        petType: post.petType,
        petGender: post.petGender,
        petName: post.petName,
        breed: post.breed,
        vaccineStatus: post.vaccineStatus || '',
        photos: post.photos || '',
        adoptionRequirement: post.adoptionRequirement || '',
        location: post.location || '',
        ownerInfo: post.ownerInfo || '',
        status: post.status
      };
      
      // 初始化文件列表
      this.fileList = [];
      this.uploadedImages = [];
      if (post.photos) {
        const images = post.photos.split(',');
        images.forEach((url, index) => {
          this.fileList.push({
            name: `image-${index}`,
            url: url
          });
          this.uploadedImages.push(url);
        });
      }
      
      this.dialogVisible = true;
    },
    
    // 重置表单
    resetForm() {
      this.postForm = {
        id: null,
        title: '',
        description: '',
        petType: '狗',
        petGender: '公',
        petName: '',
        breed: '',
        vaccineStatus: '',
        photos: '',
        adoptionRequirement: '',
        location: '',
        ownerInfo: '',
        status: '寻找中'
      };
      this.fileList = [];
      this.uploadedImages = [];
    },
    
    // 图片上传成功
    handleUploadSuccess(response, file, fileList) {
      if (response.success) {
        this.uploadedImages.push(response.data);
        this.$notify({
          title: '成功',
          message: '图片上传成功',
          type: 'success',
          duration: 2000
        });
      } else {
        this.$notify({
          title: '失败',
          message: response.message || '图片上传失败',
          type: 'error',
          duration: 2000
        });
      }
    },
    
    // 移除图片
    handleRemove(file, fileList) {
      const index = this.uploadedImages.indexOf(file.url || file.response.data);
      if (index > -1) {
        this.uploadedImages.splice(index, 1);
      }
    },
    
    // 超出限制
    handleExceed() {
      this.$notify({
        title: '提示',
        message: '最多只能上传5张图片',
        type: 'warning',
        duration: 2000
      });
    },
    
    // 提交帖子
    async submitPost() {
      // 表单验证
      if (!this.postForm.title) {
        this.$notify({
          title: '提示',
          message: '请输入标题',
          type: 'warning',
          duration: 2000
        });
        return;
      }
      
      if (!this.postForm.petName) {
        this.$notify({
          title: '提示',
          message: '请输入宠物名称',
          type: 'warning',
          duration: 2000
        });
        return;
      }
      
      if (!this.postForm.breed) {
        this.$notify({
          title: '提示',
          message: '请输入品种',
          type: 'warning',
          duration: 2000
        });
        return;
      }
      
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        
        const postData = {
          ...this.postForm,
          photos: this.uploadedImages.join(',')
        };
        
        let response;
        if (this.isEdit) {
          postData.currentUserId = userInfo.id;
          response = await updateAdoptionPost(postData);
        } else {
          postData.userId = userInfo.id;
          response = await addAdoptionPost(postData);
        }
        
        if (response.data.success) {
          this.$notify({
            title: '成功',
            message: this.isEdit ? '更新成功' : '发布成功',
            type: 'success',
            duration: 2000
          });
          this.dialogVisible = false;
          this.loadAdoptionPosts();
        } else {
          this.$notify({
            title: '失败',
            message: response.data.message || (this.isEdit ? '更新失败' : '发布失败'),
            type: 'error',
            duration: 2000
          });
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: this.isEdit ? '更新失败，请稍后重试' : '发布失败，请稍后重试',
          type: 'error',
          duration: 2000
        });
      }
    },
    handleImageLoadError(post) {
      this.$set(post, 'imageLoadError', true);
    },
    handleAvatarLoadError(post) {
      this.$set(post, 'avatarLoadError', true);
    },
    
    // 切换收藏筛选 - 预留功能
    toggleFavoriteFilter() {
      if (this.hasFavoritePosts) {
        this.searchForm.favorite = !this.searchForm.favorite;
        this.handleSearch();
      }
    },
    
    // 检查是否有收藏的帖子 - 预留功能
    checkFavoritePosts() {
      // 此功能暂未实现
      if (false) {
        this.hasFavoritePosts = true;
      }
    }
  }
};
</script>

<style scoped>
.adoption-list-container {
  min-height: calc(100vh - 130px);
  padding-bottom: 20px;
}

/* 搜索筛选区域 */
.search-section {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: flex-end;
}

.search-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.search-item label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.search-item .el-input {
  width: 200px;
}

.search-buttons {
  display: flex;
  gap: 10px;
}

/* 筛选按钮区域 */
.filter-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.filter-group {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.filter-group:last-child {
  margin-bottom: 0;
}

.filter-group > label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  min-width: 90px;
}

.filter-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-btn {
  padding: 8px 20px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.filter-btn:hover {
  color: #2c5f2d;
  border-color: #2c5f2d;
  background: #f0f9f0;
}

.filter-btn.active {
  color: white;
  background: linear-gradient(135deg, #2c5f2d 0%, #97bc62 100%);
  border-color: #2c5f2d;
  font-weight: 600;
}

/* 领养帖子网格 */
.adoption-grid {
  min-height: 400px;
}

.adoption-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
  height: 460px;
  display: flex;
  flex-direction: column;
}

.adoption-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.adoption-image {
  position: relative;
  width: 100%;
  height: 240px;
  overflow: hidden;
  background: #f5f7fa;
}

.adoption-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.adoption-card:hover .adoption-image img {
  transform: scale(1.1);
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  background: linear-gradient(135deg, #f5f5f5 0%, #e0e0e0 100%);
  gap: 10px;
}

.image-error i {
  font-size: 48px;
}

.image-error span {
  font-size: 14px;
}

.adoption-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.adoption-card:hover .adoption-overlay {
  opacity: 1;
}

.my-post-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background: linear-gradient(135deg, #f56c6c 0%, #f5222d 100%);
  color: white;
  padding: 5px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.4);
}

.adoption-info {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.adoption-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.adoption-meta {
  display: flex;
  gap: 6px;
  margin-bottom: 10px;
  flex-wrap: wrap;
}

.adoption-pet-name {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.adoption-location {
  font-size: 13px;
  color: #909399;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.adoption-location i {
  font-size: 14px;
}

.adoption-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: auto;
  padding-top: 10px;
  border-top: 1px solid #e4e7ed;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  min-width: 0;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e4e7ed;
  flex-shrink: 0;
}

.avatar-error {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: linear-gradient(135deg, #f5f5f5 0%, #e0e0e0 100%);
  border: 2px solid #e0e0e0;
  flex-shrink: 0;
}

.user-nickname {
  font-size: 13px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.action-buttons {
  flex-shrink: 0;
}

/* 分页 */
.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .search-item .el-input {
    width: 100%;
  }

  .filter-group {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .filter-group > label {
    min-width: auto;
  }

  .adoption-card {
    height: auto;
  }
}
</style>

